package org.csu.mypetstore.tools;



//import com.sun.mail.util.MailSSLSocketFactory;

import org.csu.mypetstore.domain.*;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Properties;

public class MailSender {
    public  void sendEmail(Account account , Cart cart) throws MessagingException, GeneralSecurityException {


        String receiver = account.getEmail();

        String message = "User :" + account.getUsername() + "<br>";
        Date date = new Date();//获取当前的日期
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        message = message + "Date :" + df.format(date) + "<br>";
        message = message +getMessage(cart);



        //创建一个配置文件并保存
        Properties properties = new Properties();

        properties.setProperty("mail.host","smtp.qq.com");

        properties.setProperty("mail.transport.protocol","smtp");

        properties.setProperty("mail.smtp.auth","true");


        //QQ存在一个特性设置SSL加密
       // MailSSLSocketFactory sf = new MailSSLSocketFactory();
       // sf.setTrustAllHosts(true);
       // properties.put("mail.smtp.ssl.enable", "true");
       // properties.put("mail.smtp.ssl.socketFactory", sf);

        //创建一个session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("1337491307@qq.com","xqfdaiiabavqbaac");
            }
        });

        //开启debug模式
        session.setDebug(true);

        //获取连接对象
        Transport transport = session.getTransport();

        //连接服务器
        transport.connect("smtp.qq.com","1337491307@qq.com","xqfdaiiabavqbaac");

        //创建邮件对象
        MimeMessage mimeMessage = new MimeMessage(session);

        //邮件发送人
        mimeMessage.setFrom(new InternetAddress("1337491307@qq.com"));

        //邮件接收人
        mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(receiver));

        //邮件标题
        mimeMessage.setSubject("YOUR ORDER HAS BEEN PAID SUCCESSFULLY");

        //邮件内容
        mimeMessage.setContent(message,"text/html;charset=UTF-8");

        //发送邮件
        transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());

        //关闭连接
        transport.close();
    }

    String getMessage(Cart cart)
    {
        String str = "";
        Iterator<CartItem>items = cart.getCartItems();
        int temp =  1;
        while (items.hasNext())
        {
            CartItem cartItem = items.next();
            String itemId = cartItem.getItem().getItemId();
            str = str + "Item " + String.valueOf(temp) + " :"  + itemId +"<br>";
            temp++;
        }
        return str;
    }



}
